<!--stmop  websocket -->
var stompClient;
let temp = null;
let hum = null;
let light = null;
let a = null;
let b = null;
let c = null;
let type;
let date;
$(function($) {
    var socket = new SockJS('/gs-guide-websocket');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        /*温度*/
        stompClient.subscribe("/topic/temp", function (response) {//订阅一个温度数值，希望把数值回调到前端，显示在页面上
            temp = response.body;
            $("#temp").text(temp)
        });

        //时间
        stompClient.subscribe("/topic/date", function (response) {
            date = response.body;
        });
        //传感器类型
        stompClient.subscribe("/topic/typewendu", function (response) {
            type = response.body;
        });
        stompClient.subscribe("/topic/typelight", function (response) {
            type = response.body;
        });
        //得到实时状态，并及时更新
        stompClient.subscribe("/topic/fenshan1", function (response) {//订阅一个数值，希望把数值回调到前端，显示在页面上
            let fan=response.body;
            if(fan==="of"){
                $("#fan").text("off");
            }else{
                $("#fan").text(fan);
            }
        });
        stompClient.subscribe("/topic/fenshan2", function (response) {
            let fan2=response.body;
            if(fan2==="of"){
                $("#fan2").text("off");
            }else{
                $("#fan2").text(fan);
            }
        });
        stompClient.subscribe("/topic/moshi", function (response) {
            let moshi=response.body;
            if(moshi==="of"){
                $("#autoControl").text("手动");
            }else{
                $("#autoControl").text("自动");
            }
        });
        stompClient.subscribe("/topic/lightType", function (response) {
            let lightType=response.body;
            if(lightType==="of"){
                $("#lightChange").text("off");
            }else{
                $("#lightChange").text("on");
            }
        });
        stompClient.subscribe("/topic/dianjiOn", function (response) {
            let dianjiOn=response.body;
            if(dianjiOn==="on") {
                $("#dianji").text("正转");
            }else if(dianjiOn==="of"){
                $("#dianji").text("反转");
            }else{
                $("#dianji").text("停止");
            }
        });
        stompClient.subscribe("/topic/type1", function (response) {
            let type1=response.body;
            if(type1==="of"){
                $("#autoControl").text("手动");
            }else{
                $("#autoControl").text("自动");
            }
        });

        /*湿度*/
        stompClient.subscribe("/topic/hum", function (response) {
            $("#hum").text(response.body)
            hum = response.body
        });
        //拿到最初的温度 光照度 阈值
        stompClient.subscribe("/topic/lowerTemp", function (response) {
            $("#wen1").text(response.body)
        });
        stompClient.subscribe("/topic/upperTemp", function (response) {
            $("#wen2").text(response.body)
        });
        stompClient.subscribe("/topic/upperLight", function (response) {
            $("#wen3").text(response.body)
        });

        //光照度
        stompClient.subscribe("/topic/light", function (response) {
            light= response['body'];
            $("#light").text(light);
            //2. 光照低于预警阈值时，控制步进电机正转，五秒后停止，停止后控制可调灯打开
            //3. 光照高于预警阈值时，控制步进电机反转，五秒后停止，停止后控制可调灯关闭
            // if(data3!=null && light - data3 < 0){//  light<date3
            //     open_method3("正转");
            //     sleep(5000);//五秒
            //     open_method3("关闭");//停止
            //     //可调灯打开
            //     if(lightSwitch==="off"){
            //         open_method4();
            //     }
            // }
            // if(data3!=null && light - data3 > 0){
            //     open_method4("反转");
            //     sleep(5000);
            //     open_method3("关闭");
            //     if(lightSwitch==="on"){
            //         open_method4();
            //     }
            // }
        });
    });
});

//向硬件的同学发送一条消息
function sendMessage(message) {
    let param=new URLSearchParams();
    param.append("message",message);
    axios.post("sendMessage",param);
}
/*风扇1*/
function fengshanOpen(){
    sendMessage("Hwcfs0502onT");//风扇打开
    $("#fan").text("on");//更新风扇状态
}
function fengshanClose(){
    sendMessage("Hwcfs0503offT");//风扇关闭
    $("#fan").text("off");
}
/*风扇2*/
function fengshanOpen2(){
    sendMessage("Hwcfd0502onT");//风扇打开
    $("#fan2").text("on");
}
function fengshanClose2(){
    sendMessage("Hwcfd0503offT");//风扇关闭
    $("#fan2").text("off");
}

/*步进电机*/
function open_method3 () {
    //步进电机正转
    sendMessage("Hwcdj0302onT")
    /*发送完请求后改变web端的状态*/
    $("#dianji").text("正转");
}
function open_method4 () {
    //步进电机反转
    sendMessage("Hwcdj0303offT")
    /*发送完请求后改变web端的状态*/
    $("#dianji").text("反转");
}
function open_method40() {
    //步进电机停止
    sendMessage("Hwcdj030200T")
    /*发送完请求后改变web端的状态*/
    $("#dianji").text("停止");
}

/*可调灯打开*/
function open_method5(){
    sendMessage("Hwcbu0302onT");//打开可调灯
    /*发送完请求后改变web端的状态*/
    $("#lightChange").text("on");
}
/*可调灯关闭*/
function open_method6(){
    sendMessage("Hwcbu0303offT");//关闭可调灯
    /*发送完请求后改变web端的状态*/
    $("#lightChange").text("off");
}
/*模式转换*/
/*自动控制*/
function open_method7(){
    sendMessage("Hwcat0302onT")
    sendMessage("Hwcat0502onT")
    $("#autoControl").text("自动");
}
/*手动模式*/
function open_method8(){
    sendMessage("Hwcat0303offT")
    sendMessage("Hwcat0503offT")
    $("#autoControl").text("手动");
}

/*处理输入框数据*/
let data1
function submitBtn1(){
    data1 = $("#max1").val();
    //Hwcih050200T
    sendMessage('Hwcih0502'+data1+'T');
    $("#wen1").text("data1");
    alert("设置成功")
}
let data2;
function submitBtn2(){
     data2 = $("#max2").val();
    //Hwcil050200T
    sendMessage('Hwcil0502'+data2+'T');
    $("#wen2").text("data2");
    alert("设置成功")
}
let data3;
function submitBtn3(){
    data3 = $("#max3").val();
    //Hwclv0306000000T
    sendMessage('Hwclv0306'+data3+'T');
    $("#wen3").text("data3");
    alert("设置成功")
}
// //启动之后发ask询问帧
// $(function () {
//     sendMessage("Hwcla0603askT");
// })

/**
 * 由于js是单线程，没有sleep函数，所以用线程堵塞的方式实现
 * 参数n为休眠时间，单位为毫秒
 */
function sleep(n) {
    let start = new Date().getTime();
    while (true) {
        if (new Date().getTime() - start > n) {
            break;
        }
    }
}

//温湿度数据折线图----------------------------------------------------------------------------------------
let chartDom = document.getElementById('line');
let myChart = echarts.init(chartDom);
let option;
let eChartTitle='温湿度数据';
let yValue=50;//y轴的值
let app={};
option = {
    title: {
        text: '温度数据(时间)',
    },
    //提示框
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross',
            label: {
                backgroundColor: '#283b56'
            }
        }
    },
    legend: {
        data:[eChartTitle]
    },//工具框
    toolbox: {
        show: true,
        feature: {
            dataView: {readOnly: false},
            restore: {},
            saveAsImage: {}//下载工具
        }
    },
    dataZoom: {
        show: false,
        start: 0,
        end: 100
    },
    xAxis: [
        {
            type: 'category',
            boundaryGap: true,
            data: (function (){
                let now = new Date();
                var res = [];
                var len = 5;
                while (len--) {
                    res.unshift(now.toLocaleTimeString().replace(/^\D*/,''));
                    now = new Date("now-2000");
                }
                return res;
            })()
        },
        {
            type: 'category',
            boundaryGap: true,
            data: (function (){
                let res = [];
                let len = 5;
                while (len--) {
                    res.push(5 - len - 1);
                }
                return res;
            })()
        }
    ],
    yAxis: [
        {
            type: 'value',
            scale: true,
            name: '索引',
            max: yValue,
            min: 0,
            boundaryGap: []
        },
        {
            type: 'value',
            scale: true,
            name: '',
            max: yValue,
            min: 0,
            boundaryGap: []
        }
    ],
    series: [
        {
            name: "温度",
            type: 'line', //图的类型
            data:
                (function (){
                    var res = [];
                    var len = 5;
                    while (len--) {
                        res.push(Math.round(date));
                    }
                    return res;
                })()
        },
    ]
};
app.count = 5;
setInterval(function () {
    let axisData = (new Date()).toLocaleTimeString().replace(/^\D*/, '');
    let data1 = option.series[0].data;
    data1.shift();
    data1.push(temp);
    option.xAxis[0].data.shift();
    option.xAxis[0].data.push(axisData);
    option.xAxis[1].data.shift();
    option.xAxis[1].data.push(app.count++);
    myChart.setOption(option);
},3000)

// 湿度柱状图
let chartDom1 = document.getElementById('line1');
let myChart1 = echarts.init(chartDom1);
let option1;
let app1={};
yValue=75;
option1 = {
    title: {
        text: '湿度数据(时间)',
    },
    //提示框
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross',
            label: {
                backgroundColor: '#c7deff'
            }
        }
    },
    legend: {
        data:eChartTitle,
    },//工具框
    toolbox: {
        show: true,
        feature: {
            dataView: {readOnly: false},
            restore: {},
            saveAsImage: {}//下载工具
        }
    },
    dataZoom: {
        show: false,
        start: 0,
        end: 100
    },
    xAxis: [
        {
            type: 'category',
            boundaryGap: true,
            data: (function (){
                let now = new Date();
                var res = [];
                var len = 5;
                while (len--) {
                    res.unshift(now.toLocaleTimeString().replace(/^\D*/,''));
                    now = new Date("now-2000");
                }
                return res;
            })()
        },
        {
            type: 'category',
            boundaryGap: true,
            data: (function (){
                let res = [];
                let len = 5;
                while (len--) {
                    res.push(5 - len - 1);
                }
                return res;
            })()
        }
    ],
    yAxis: [
        {
            type: 'value',
            scale: true,
            name: '索引',
            max: yValue,
            min: 0,
            boundaryGap: []
        },
        {
            type: 'value',
            scale: true,
            name: '',
            max: yValue,
            min: 0,
            boundaryGap: []
        }
    ],
    series: [
        {
            name: "湿度",
            type: 'bar', //图的类型
            data:
                (function (){
                    var res = [];
                    var len = 5;
                    while (len--) {
                        res.push(Math.round(date));
                    }
                    return res;
                })()
        },
    ]
};
app1.count = 5;
setInterval(function () {
    let axisData1 = (new Date()).toLocaleTimeString().replace(/^\D*/, '');
    let data1 = option1.series[0].data;
    data1.shift();
    data1.push(hum);
    option1.xAxis[0].data.shift();
    option1.xAxis[0].data.push(axisData1);
    option1.xAxis[1].data.shift();
    option1.xAxis[1].data.push(app1.count++);
    myChart1.setOption(option1);
},3000)
// 湿度柱状图
let chartDom2 = document.getElementById('line2');
let myChart2= echarts.init(chartDom2);
let option2;
let app2={};
yValue=250;
option2 = {
    title: {
        text: '光照度数据(传感器类型)',
    },
    //提示框
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross',
            label: {
                backgroundColor: '#c7deff'
            }
        }
    },
    legend: {
        data:eChartTitle,
    },//工具框
    toolbox: {
        show: true,
        feature: {
            dataView: {readOnly: false},
            restore: {},
            saveAsImage: {}//下载工具
        }
    },
    dataZoom: {
        show: false,
        start: 0,
        end: 100
    },
    xAxis: [
        {
            type: 'category',
            boundaryGap: true,
            data: (function (){
                let now = new Date();
                var res = [];
                var len = 5;
                while (len--) {
                    res.unshift(now.toLocaleTimeString().replace(/^\D*/,''));
                    now = new Date("now-2000");
                }
                return res;
            })()
        },
        {
            type: 'category',
            boundaryGap: true,
            data: (function (){
                let res = [];
                let len = 5;
                while (len--) {
                    res.push(5 - len - 1);
                }
                return res;
            })()
        }
    ],
    yAxis: [
        {
            type: 'value',
            scale: true,
            name: '索引',
            max: yValue,
            min: 0,
            boundaryGap: []
        },
        {
            type: 'value',
            scale: true,
            name: '',
            max: yValue,
            min: 0,
            boundaryGap: []
        }
    ],
    series: [
        {
            name: "光照度",
            type: 'line', //图的类型
            data:
                (function (){
                    var res = [];
                    var len = 5;
                    while (len--) {
                        res.push(Math.round(date));
                    }
                    return res;
                })()
        },
    ]
};
app2.count = 5;
setInterval(function () {
    let axisData2 = (new Date()).toLocaleTimeString().replace(/^\D*/, '');
    let data2 = option2.series[0].data;
    data2.shift();
    data2.push(light);
    option2.xAxis[0].data.shift();
    option2.xAxis[0].data.push(axisData2);
    option2.xAxis[1].data.shift();
    option2.xAxis[1].data.push(app2.count++);
    myChart2.setOption(option2);
},3000)